package org.restoran.service.parser.jackson;

import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonProcessingException;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;
import org.restoran.model.Item;
import org.restoran.model.ItemOrder;
import org.restoran.service.ItemService;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.IOException;

/**
 * @author Snisar Bogdan.
 */
public class ItemOrderBeanDeserialyze extends JsonDeserializer<ItemOrder> {

    private static final String ID_KEY = "id";
    private static final String COUNT = "id";


    @Override
    public ItemOrder deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ItemOrder oi = new ItemOrder();
        Integer itemId = null, count = null;
        JsonToken token;

        if(jp.getCurrentToken() ==JsonToken.START_OBJECT){
            while ((token = jp.nextToken()) != null && token != JsonToken.END_OBJECT) {
                String prop = jp.getCurrentName();
                if(ID_KEY.equalsIgnoreCase(prop)) {
                    token = jp.nextToken();
                    itemId = getIntValue(jp);
                    continue;
                }
                if(COUNT.equalsIgnoreCase(prop)) {
                    token = jp.nextToken();
                    count = getIntValue(jp);
                }
            }
        }
        Item i = new Item();
        i.setId(itemId);

        oi.setCount(count);
        oi.setItem(i);
        return oi;
    }



    private Integer getIntValue(JsonParser jp) throws IOException {
        Integer i; JsonToken t = jp.getCurrentToken();

        if(t.isNumeric()) {
            return jp.getValueAsInt();
        } else if(t == JsonToken.VALUE_STRING) {
            String text = jp.getText();
            return Integer.parseInt(text);
        }
        return null;

    }


}
